import torch

class GradientCalculator:
    @staticmethod
    def compute(grad: torch.Tensor, metrics: list) -> dict:
        results = {}
        grad = grad.float()  # 统一计算精度
        
        if "norm" in metrics:
            results["norm"] = torch.linalg.vector_norm(grad).item()
        
        if any(m in metrics for m in ["max", "min", "mean"]):
            flat_grad = grad.flatten()
            
            if "max" in metrics:
                results["max"] = torch.max(flat_grad).item()
            if "min" in metrics:
                results["min"] = torch.min(flat_grad).item()
            if "mean" in metrics:
                results["mean"] = torch.mean(flat_grad).item()
        
        return results
